package main

import (
	"WeChatMGRA/server/conf"
	"WeChatMGRA/server/control"
	"WeChatMGRA/server/smodul"
	"WeChatMGRA/server/util"
	"fmt"
	"gitee.com/yutiandou/wdtools/wdevent"
	"gitee.com/yutiandou/wdtools/wdlog"
	"gitee.com/yutiandou/wdtools/wdutil"
	"github.com/gin-gonic/gin"
)

//debug:调试模式  release:发行模式
const Mode = "release"

func main(){
	wdutil.RunDaemonByFlag()
	util.SystemQuit(func(){
		wdlog.Warning("系统退出")
		wdevent.ExecEvent("gameover",nil)
	})
	defer func(){
		if err:=recover();err!=nil{
			wdlog.Warning("系统异常")
			wdevent.ExecEvent("gameover",nil)
		}
	}()
	log_config_db_init()
	//开启监听服务
	control.StartReceiveServer(conf.Global_Conf)
	//用户服务开启服务
	server:=gin_init()
	server.Run( fmt.Sprintf("%s:%s",conf.Global_Conf.Address,conf.Global_Conf.Port))
}
//log_config_db_init ..初始化日志，加载配置文件，连接数据库
func log_config_db_init()*conf.Config{
	//设置日志文件
	switch Mode {
	case "debug":
		wdlog.SetLogLevel(wdlog.W_Debug)
		wdlog.SetLogToTerminal()
	case "release":
		wdlog.SetLogLevel(wdlog.W_Warning)
		wdlog.SetLogToDirectory("./log/",1048576)
		wdevent.AddEvent("MysqlCloseSuccess",func(data interface{}){
			wdlog.StopWDLog()
		})
	}
	wdlog.SetLogOptions( wdlog.W_CallName | wdlog.W_Line)
	wdlog.Warning("日志模块初始化完成...")
	//加载服务器配置
	config,err:= conf.LoadConfig("./conf/config.yaml")
	if wdlog.PanicErr(err){
		return nil
	}
	wdlog.Warning("配置模块加载完成...")
	//连接并设置数据库
	if err = smodul.ConnectDB(config);wdlog.PanicErr(err){
		return nil
	}
	wdevent.ExecEvent("MysqlConnectSuccess",smodul.MysqlDB)
	return config
}

//gin_init gin实例路由初始化
func gin_init() * gin.Engine{
	if Mode == "release"{
		gin.SetMode(gin.ReleaseMode)
	}
	server:=gin.New()
    //server:=gin.Default()
    server.Use(gin.Recovery())
	control.Gin_Config_Init(conf.Global_Conf)
	control.Gin_Global_Middle_Init(server)
	control.Gin_Router_Init(server)
	wdlog.Warning("用户服务配置完成...")
	return  server
}